package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfos;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Mt;
import cn.stylefeng.guns.sys.modular.system.entity.BtyDkmx;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMtyq;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMtyqMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMtyqParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyMtyqResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyMtyqService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.codec.binary.Hex;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuy
 * @since 2021-07-29
 */
@Service
public class BtyMtyqServiceImpl extends ServiceImpl<BtyMtyqMapper, BtyMtyq> implements BtyMtyqService {

    @Override
    public void add(BtyMtyqParam param){
        BtyMtyq entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyMtyqParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyMtyqParam param){
        BtyMtyq oldEntity = getOldEntity(param);
        BtyMtyq newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchImportTxt(String fileName, MultipartFile multipartFile) {
        boolean notNull = false;
        try {
            //截取日期
            String dealTime=null;
            if(fileName.length()>8) {
                dealTime = fileName.substring(0, 8);
            }
            if(null!=multipartFile){
                String suffixName=fileName.substring(fileName.lastIndexOf("."));
                if(suffixName.equals(".txt")){
                    FileInputStream fileInputStream=(FileInputStream)multipartFile.getInputStream();
                    InputStreamReader isr=new InputStreamReader(fileInputStream,"utf-8");
                    BufferedReader br=new BufferedReader(isr);
                    String lineTxt;
                    //br.readLine();//忽略第一行标题
                    while((lineTxt=br.readLine())!=null) {
                        String[] s = lineTxt.split("\\r");
                        String codes = s[0];
                        System.out.println("code:" + codes);
                        if (ToolUtil.isNotEmpty(codes)) {
                        String appKey = "ebf8340f8ba7cb0327173299f689c9d8c664b1f4";
                        String appSecret = "49c6be3b34eb165ccfa0bb167f6799fe6ed81cc2";
                        String ts = String.valueOf(System.currentTimeMillis());
                        String version = "2.0";
                        JSONObject json = new JSONObject();
                        json.put("couponCode", codes);
                        json.put("vendorShopId", "957299785");
                        String four = json.toJSONString();
                        String[] params = new String[]{appSecret, "appKey" + appKey, "ts" + ts, "version" + version, four};
                        Arrays.sort(params);
                        // 将5个参数字符串拼接成一个字符串进行sha1加密
                        String clearText = params[0] + params[1] + params[2] + params[3] + params[4];
                        String algorithm = "SHA-1";
                        String sign = new String(Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes()), true));
                        RestTemplate restTemplate = new RestTemplate();
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
                        String url = "https://open-api.dianping.com/tuangou/coupon/status/query?version=" + version + "&appKey=" + appKey + "&ts=" + ts + "&sign=" + sign;
                        String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                        Mt mt = restTemplate.postForEntity(url, formEntity, Mt.class).getBody();
                        System.out.println("result:" + result);
                        JsonParser jp = new JsonParser();
                        //将json字符串转化成json对象
                        JsonObject jo = jp.parse(result).getAsJsonObject();
                        //获取code对应的值
                        String code = jo.get("code").getAsString();

                        if (mt.getCode() == 200) {
                            Mt.ContentBean bean = mt.getContent();
                            //通过券码查询是否已经存在记录
                            BtyMtyq yq=baseMapper.selectOne(new QueryWrapper<BtyMtyq>().eq("code",codes));
                            if(ToolUtil.isNotEmpty(yq)){
                                yq.setState(bean.getStatus());
                                baseMapper.updateById(yq);
                            }else {
                                BtyMtyq mtyq = new BtyMtyq();
                                mtyq.setId(UUIDUtils.getId());
                                //门店id
                                mtyq.setMdid("957299785");
                                mtyq.setDm("东更道测试门店");
                                mtyq.setName(bean.getDealTitle());
                                mtyq.setType(bean.getDealType());
                                mtyq.setCode(codes);
                                mtyq.setState(bean.getStatus());
                                //实收金额realAmount
                                mtyq.setAmount(bean.getRealAmount());
                                mtyq.setCreateTime(new Date());
                                baseMapper.insert(mtyq);
                            }
                        }

                    }


//                        btyDkmx.setCreateTime(new Date());
//                        baseMapper.insert(mtyq);
                    }
                    notNull=true;
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return notNull;
    }

    @Override
    public BtyMtyqResult findBySpec(BtyMtyqParam param){
        return null;
    }

    @Override
    public List<BtyMtyqResult> findListBySpec(BtyMtyqParam param){
        return null;
    }

    @Override
    public List<BtyMtyqResult> dmList(BtyMtyqParam param) {
        return baseMapper.dmList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyMtyqParam param){
        if (ToolUtil.isNotEmpty(param.getCjsj())) {
            String[] split = param.getCjsj().split(" - ");
            String   beginTime = split[0];
            String   endTime = split[1] + " 23:59:59";
//            String beginTime=param.getCjsj().substring(0,10);
//            String endTime=beginTime+ " 23:59:59";
            param.setBeginTime(beginTime);
            param.setEndTime(endTime);
        }
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfos findPageByList(BtyMtyqParam param){
        if (ToolUtil.isNotEmpty(param.getCjsj())) {
            String beginTime=param.getCjsj().substring(0,10);
            String endTime=beginTime+ " 23:59:59";
            param.setBeginTime(beginTime);
            param.setEndTime(endTime);
        }
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfos(page);
    }

    /**
     * 实付金额分类：0、当日实付金额，1、本月实付金额，2、本季度实付金额，3、近半年实付金额，4、近一年实付金额
     * @param param
     * @return
     */
    @Override
    public BigDecimal amount(BtyMtyqParam param) {
        Integer amountType=param.getAmountType();

        if(amountType==0){
            String beginTime=DateUtil.getNowDate();
            String endTime=beginTime+ " 23:59:59";
            param.setBeginTime(beginTime);
            param.setEndTime(endTime);
        }else if(amountType==1){
            String month=DateUtil.getCurrentMonth();
            param.setMonth(month);
        }else if(amountType==2){
            List<String> monthList = new ArrayList<>();
            //获取当前月的上个月
            String lastMonth=DateUtil.getLastMonthStr();
            //获取当前月
            String month=DateUtil.getCurrentMonth();
            String nextMonth=DateUtil.getNextMonthStr();
            monthList.add(lastMonth);
            monthList.add(month);
            monthList.add(nextMonth);
            String[] months = monthList.toArray(new String[monthList.size()]);
            param.setMonths(months);
        }else if(amountType==3){
            //获取当前月
            String month=DateUtil.getCurrentMonth();
            String sixMonth=DateUtil.getSixMonthStr();
            param.setMonth(month);
            param.setSixMonth(sixMonth);
        }else if(amountType==4){
            //获取当前月
            String month=DateUtil.getCurrentMonth();
            String months=DateUtil.getYeatStr();
            param.setMonth(month);
            param.setTwelveMonth(months);
        }
        return baseMapper.amount(param);
    }

    private Serializable getKey(BtyMtyqParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyMtyq getOldEntity(BtyMtyqParam param) {
        return this.getById(getKey(param));
    }

    private BtyMtyq getEntity(BtyMtyqParam param) {
        BtyMtyq entity = new BtyMtyq();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
